import { _decorator, Collider2D, Component, Contact2DType, Node } from 'cc';
import { Enemy } from './Enemy';
const { ccclass, property } = _decorator;



@ccclass('Bullet1')
export class Bullet1 extends Component {
    //子弹飞行速度
    @property
    speed = 500

    @property(Collider2D)
    collider: Collider2D = null

    start() {
        //碰撞检测
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onContact, this);
        }
    }

    update(deltaTime: number) {
        //移动
        const position = this.node.position
        this.node.setPosition(position.x, position.y + this.speed * deltaTime, position.z)
        //出屏自毁
        if (position.y > 440) {
            this.node.destroy()
        }
    }

    onContact(self, other: Collider2D) {
        console.log('子弹击中目标');
        //获取节点名称
        const selfName = self.node.name
        const otherName = other.node.name
        //获取接触物体的自定义脚本组件
        const otherScript = other.node.getComponent('Enemy')
        console.log(otherScript);
        
        //判断该脚本是否是Enemy脚本
        if (otherScript instanceof Enemy) {
            //声明一个变量用来接收敌人受伤方法的调用结果
            const result = {flag : false, state: '变量声明阶段'}
            //调用敌人受伤方法
            otherScript.hit(1, result)
            //@ts-ignore   //忽略编辑器不知道result将会被赋值的错误
            //如果调用成功
            if (result.flag == true) {
                //子弹因为使敌人受伤而自毁
                this.node.destroy()
            }
            console.log(result.state);
        }

        console.log(`${selfName} 接触到物体 ${otherName}`);
    }
}


